package com.common.library.ui.view.pager;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.library.R;
import com.common.library.tools.StringTools;

import java.util.List;


/**
 * ViewPager滑动指示器
 */
public class ViewPagerIndicator extends LinearLayout {
    private static final String TAG = "ViewPagerIndicator";
    private OnPageChangeListener mPageChangeListener;//ViewPager页面变化监听器
    private ViewPager mViewPager;//关联的ViewPager
    private int mWidth;//选择器一屏所占的宽度
    private int mTabVisibleCount;//一屏可见tab数量
    private int COLOR_TEXT_DARK;//Tab文本未选中的默认颜色
    private int COLOR_TEXT_LIGHT;//Tab文本选中的默认颜色
    private int TAB_TEXT_SIZE;//Tab 默认字体大小 sp

    public ViewPagerIndicator(Context context) {
        super(context);
        init();
    }

    public ViewPagerIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void setWidth(int dp) {
        mWidth = dp;
    }

    /**
     * 初始化
     */
    private void init() {
        mWidth = getScreenWidth();//选择器一屏所占的宽度
        mTabVisibleCount = 4;//可见tab数量
        COLOR_TEXT_DARK = getResources().getColor(R.color.half);//Tab文本未选中的默认颜色
        COLOR_TEXT_LIGHT = getResources().getColor(R.color.orange);//Tab文本选中的默认颜色
        TAB_TEXT_SIZE = 15;//Tab 默认字体大小 sp
    }
    /**
     * 确定显示子View的个数
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int cCount = getChildCount();
        if (cCount == 0) return;
        for (int i = 0; i < cCount; i++) {
            View view = getChildAt(i);
            LayoutParams lp = (LayoutParams) view.getLayoutParams();
            lp.weight = 0;
            lp.width = mWidth / mTabVisibleCount;
            view.setLayoutParams(lp);
        }
    }
    /**
     * 设置点击Tab切换ViewPager的Item
     */
    private void setClickTabEvent(int count) {
        for (int i = 0; i < count; i++) {
            final int pos = i;
            final View view = getChildAt(i);
            if (view instanceof TextView) {
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mViewPager != null)
                            mViewPager.setCurrentItem(pos);
                    }
                });
            }
        }
    }

    /**
     * 获得屏幕的宽度
     */
    private int getScreenWidth() {
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }
    /**
     * @param tabVisibleCount 设置一屏Tab可见数量
     */
    public void setTabVisibleCount(int tabVisibleCount) {
        mTabVisibleCount = tabVisibleCount;
    }

    /**
     * @param titles 根据titles设置Tab
     */
    public void setTabItemTitles(List<String> titles) {
        if (titles == null && titles.size() == 0) return;
        this.removeAllViews();
        for (String title : titles) {
            if (!StringTools.isNull(title))
                this.addView(getTextView(title));
        }
        if (getChildCount() != 0) {
            setClickTabEvent(getChildCount());
        }
    }
    /**
     * @param title 根据title 返回TextView实例
     */
    private View getTextView(String title) {
        LayoutParams lp = new LayoutParams(mWidth / mTabVisibleCount, LayoutParams.MATCH_PARENT);
        TextView tv = new TextView(getContext());
        tv.setTextColor(COLOR_TEXT_DARK);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_TEXT_SIZE);
        tv.setGravity(Gravity.CENTER);
        tv.setText(title);
        tv.setLayoutParams(lp);
        return tv;
    }

    /**
     * 重置文本颜色
     */
    private void ResetTextColor() {
        int Ccount = getChildCount();
        for (int i = 0; i < Ccount; i++) {
            View view = getChildAt(i);
            if (view instanceof TextView) {
                ((TextView) view).setTextColor(COLOR_TEXT_DARK);
            }
        }
    }

    /**
     * @param pos 设置某一个Tab文本的颜色为高亮
     */
    private void setTextLightColor(int pos) {
        if (getChildCount() == 0) return;
        View view = getChildAt(pos);
        if (view instanceof TextView) {
            ((TextView) view).setTextColor(COLOR_TEXT_LIGHT);
        }
    }

    /**
     * ViewPager Item选择监听接口
     */
    public interface OnPageChangeListener {
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);

        public void onPageSelected(int position);

        public void onPageScrollStateChanged(int state);

    }
    /**
     * @param pageChangeListener 设置ViewPager Item选择监听
     */
    public void addOnPageChangeListener(OnPageChangeListener pageChangeListener) {
        mPageChangeListener = pageChangeListener;
    }
    /**
     * 设置关联的ViewPager
     *
     * @param pos 默认显示item的位置
     */
    public void setViewPager(ViewPager viewPager, int pos) {
        if (viewPager == null) return;
        mViewPager = viewPager;
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                setScroll(position,positionOffset);
                if (mPageChangeListener != null) {
                    mPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                ResetTextColor();
                setTextLightColor(position);
                if (mPageChangeListener != null) {
                    mPageChangeListener.onPageSelected(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (mPageChangeListener != null) {
                    mPageChangeListener.onPageScrollStateChanged(state);
                }
            }
        });
        mViewPager.setCurrentItem(pos, true);
        ResetTextColor();
        setTextLightColor(pos);
    }
    private void setScroll(int position, float positionOffset) {
        int tabwidth = mWidth / mTabVisibleCount;
        //容器移动
        if (getChildCount() > mTabVisibleCount && position >= (mTabVisibleCount - 2) && positionOffset > 0) {
            if (mTabVisibleCount != 1 && position < getChildCount() - 2) {
                ((HorizontalScrollView) getParent()).scrollTo((position - (mTabVisibleCount - 2)) * tabwidth + (int) (tabwidth * positionOffset), 0);
            }
        } else if (mTabVisibleCount == 1) {
            ((HorizontalScrollView) getParent()).scrollTo(position * tabwidth + (int) (tabwidth * positionOffset), 0);
        }
        invalidate();
    }
    /**
     * @param titles    根据titles设置Tab
     * @param viewPager 关联的ViewPager
     * @param pos       关联ViewPager的item默认选中的位置
     */
    public void setTabIndicator(List<String> titles, ViewPager viewPager, int pos) {
        setTabItemTitles(titles);
        setViewPager(viewPager, pos);
    }
    /**
     * @param titles          根据titles设置Tab
     * @param viewPager       关联的ViewPager
     * @param pos             关联ViewPager的item默认选中的位置
     * @param tabVisibleCount 一屏可见Tab数量
     */
    public void setTabIndicator(List<String> titles, ViewPager viewPager, int pos, int tabVisibleCount) {
        setTabVisibleCount(tabVisibleCount);
        setTabItemTitles(titles);
        setViewPager(viewPager, pos);
    }
}
